
import axios from 'axios'
import {Message} from 'view-design';
import {clientId} from "@/config/config";
// 创建一个axios实例
const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
    timeout: 30000, // 请求超时时间 默认30秒
    headers: {
        'Content-Type': 'application/json'
    }
})
// 请求拦截器
service.interceptors.request.use(config => {
        const token = sessionStorage.getItem('userToken');
        // 判断是否存在token，如果存在的话，则每个http header都加上token
        if (token) {
            config.headers['Authorization'] ='Bearer '+ token
        }
        return config
    },
    error => {
        // debug
        console.log(error)
        return Promise.reject(error)
    }
)

// 响应拦截器
service.interceptors.response.use(
    response => {
        const res = response.data
        if (res.code===401){
            sessionStorage.removeItem('userToken')
            sessionStorage.removeItem('isLogin')
            window.location.href = location.origin+'/login?clientId='+clientId
        }
        if (res.code !== 200) {
            Message.warning(res.message || 'Error')
            return Promise.reject(new Error(res.message || 'Error'))
        } else {
            return res.result
        }
    },
    error => {
        if (error && error.response && error.response.status) {
            switch (error.response.status) {
                case 500:
                    break
                case 401:
                    sessionStorage.removeItem('userToken')
                    sessionStorage.removeItem('isLogin')
                    window.location.href = location.origin+'/login?clientId='+clientId
                    break
                 case 455:
                     Message.error('被限流了，请稍等片刻提交请求！' || 'Error')
                     break
                default:
                    Message.error(error.message || 'Error')
                    break
            }
        }
        return Promise.reject(error)
    }
)

export default service
